<template>
 <div>
   <!-- 面包屑导航 -->
    <el-breadcrumb>
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 页面内容 -->
<el-card>
  <el-row :gutter="20">
  <el-col :span="9">
    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUserList'>
    <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
  </el-input>
  </el-col>
  <el-col :span="4">
    <el-button type="primary" @click="addUserVisible = !addUserVisible">添加用户</el-button>
    </el-col>
</el-row>
<!-- 用户列表区域 -->
  <el-table :data="userList"  stripe border >
    <el-table-column type="index"></el-table-column>
    <el-table-column prop="username" label="姓名" ></el-table-column>
    <el-table-column prop="email" label="邮箱" ></el-table-column>
    <el-table-column prop="mobile" label="电话" ></el-table-column>
    <el-table-column prop="role_name" label="角色" ></el-table-column>
    <el-table-column label="状态" >
      <template slot-scope="scope">
        <el-switch v-model="scope.row.mg_state" @change="updataUserState(scope.row)">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width='220'>
      <template slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
        <el-button type="danger" icon="el-icon-delete" @click="deleteUserInfo(scope.row.id)"></el-button>
        <el-tooltip  content="角色分配" placement="top" :enterable=false>
           <el-button type="warning" icon="el-icon-setting" @click="setRoles(scope.row)"></el-button>
         </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <!-- 页码跳转区域 -->
   <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>
 <!-- 添加用户对话框区域 -->
 <el-dialog
  title="添加用户"
  :visible.sync="addUserVisible"
  width="50%"
  @close='beforeDialogClose'>
  <!-- visible.sync动态属性绑定控制对话框的显示与隐藏 -->
  <!-- 添加用户表单 -->
  <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username" clearable></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password" clearable type="password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email" clearable></el-input>
  </el-form-item>
  <el-form-item label="手机" prop="mobile">
    <el-input v-model="addForm.mobile" clearable></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addUserVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改用户信息对话框区域 -->
<el-dialog
  title="修改用户信息"
  :visible.sync="editUserVisible"
  width="30%"
  @close='resetFormRules'
  >
  <!-- 修改用户表单区域 -->
  <el-form ref="editFormRef" :model="userInfo" label-width="80px" :rules="editFormRules">
  <el-form-item label="用户名">
    <el-input v-model="userInfo.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop='email' >
    <el-input v-model="userInfo.email" ></el-input>
  </el-form-item>
  <el-form-item label="手机号" prop='mobile' >
    <el-input v-model="userInfo.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editUserVisible = false">取 消</el-button>
    <el-button type="primary" @click="PreVerification">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配用户角色页面 -->
<el-dialog
  title="分配角色"
  width="50%"
  :visible.sync="rolesDialogVisible" @close='resetRole'
  >
  <div>
    <p>当前的用户：{{userInfo.username}}</p>
    <p>当前的角色：{{userInfo.role_name}}</p>
    <p>分配新角色：
       <el-select v-model="selectRole" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
    </p>
  </div>
  <span slot="footer" class="rolesDialogVisible">
    <el-button @click="rolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>
 </div>
</template>
<script>
export default {
  data() {
    // 自定义表单验证规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱
      const reg = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('邮箱不合法'))
    }
    // 验证手机号
    var checkMobile = (rule, value, callback) => {
      const reg = /^1[35678]\d{9}$/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('手机号不合法'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1, // 当前页码数
        pagesize: 2 // 每页的显示条数
      },
      total: 0, // 总的信息条数
      userList: [],
      // 对话框的显示与隐藏
      addUserVisible: false,
      // 修改对话框的显示与隐藏
      editUserVisible: false,
      // 修改用户表单信息
      userInfo: {},
      // 获取所有角色列表
      rolesList: [],
      // 当前选择的用户角色
      selectRole: '',
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 6, message: '请输入2-6位用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6-16位密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱!', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号!', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改表单验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱!', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号!', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制角色分配对话框的显示与隐藏
      rolesDialogVisible: false
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 页面一上来就获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 当每页显示用户条数发生改变时，
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 当前页码数发生改变时触发该事件
    handleCurrentChange(newpage) {
      // console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 修改用户状态
    async updataUserState(usermsg) {
      const { data: res } = await this.$http.put(`users/${usermsg.id}/state/${usermsg.mg_state}`)
      if (res.meta.status !== 200) {
        // 当用户修改状态失败时，把页面中开关的状态修改过来
        usermsg.mg_state = !usermsg.mg_state
        return this.$message.error('用户状态修改失败！')
      }
      this.$message.success('用户状态修改成功!')
    },
    // 监听关闭dialog对话框事件
    beforeDialogClose() {
      // console.log(this)
      // 清除表单内容和验证规则
      this.$refs.addFormRef.resetFields()
    },
    // 表单的预校验
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('添加用户失败')
        // 如果表单验证通过，调用接口添加用户
        const { data: res } = await this.$http.post('/users', this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('用户添加失败！')
        this.$message.success('用户添加成功！')
        // 关闭对话框
        this.addUserVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    // 修改用户对话框
    async showEditDialog(userId) {
      // console.log(userId)
      // 根据用户id查询用户信息
      const { data: res } = await this.$http.get('users/' + userId)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('修改用户失败!')
      // 把返回的用户信息传给数据对象userInfo
      this.userInfo = res.data
      // 点击编辑按钮打开对话框
      this.editUserVisible = true
    },
    // 当关闭修改表单对话框前，清除当前表单验证规则
    resetFormRules() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改表单预验证
    PreVerification() {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('格式不合法！')
        }
        // 调用接口修改用户信息
        const { data: res } = await this.$http.put('users/' + this.userInfo.id, this.userInfo)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('用户信息修改失败！')
        this.$message.success('用户信息修改成功！')
        this.getUserList()
        // 关闭修改用户页面
        this.editUserVisible = false
      })
    },
    // 点击按钮删除用户信息
    async deleteUserInfo(userId) {
      // console.log(userId)
      // 弹框询问用户是否删除
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => { return err })
      // console.log(result)
      // 点击确定返回confirm
      // 点击取消返回cancel
      if (result === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + userId, { params: userId })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.getUserList()
        this.$message.success(res.meta.msg)
      } else {
        this.$message('已取消删除')
      }
    },
    // 分配用户角色
    async setRoles(userInfo) {
      this.userInfo = userInfo
      // 在展示对话框之前获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.rolesList = res.data
      this.rolesDialogVisible = true
    },
    // 保存用户角色信息
    async saveRoleInfo() {
      // 先判断用户是否选择了新的角色
      if (!this.selectRole) return this.$message.error('请选择用户角色！')
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRole })
      if (res.meta.status !== 200) return this.$message.error('分配用户角色失败！')
      this.$message.success('分配用户角色成功！')
      this.getUserList()
      this.rolesDialogVisible = false
    },
    resetRole() {
      this.selectRole = ''
      this.userInfo = {}
    }
  }
}

</script>
<style lang="less" scoped>
</style>
